import React, { useEffect, useRef } from 'react';
import { ProFormField } from '@ant-design/pro-components';
import JSONEditor from 'jsoneditor';
import 'jsoneditor/dist/jsoneditor.css';

const ProFormJSONEditor = ({ height = 400, editorOptions, ...rest }) => {
  return (
    <ProFormField
      {...rest}
      valueType="json"
      renderFormItem={(schema, config, form) => {
        const containerRef = useRef(null);
        const editorRef = useRef(null);
        const { value, onChange, initialValue } = config.fieldProps || {};

        // 初始化 JSONEditor
        useEffect(() => {
          if (!containerRef.current) return;

          editorRef.current = new JSONEditor(containerRef.current, {
            mode: 'code', // 默认 code 模式，可改 tree
            onChange: () => {
              try {
                const updated = editorRef.current.get();
                onChange?.(updated);
              } catch (e) {
                // 忽略非法 JSON
              }
            },
            ...editorOptions,
          });

          // 初始值优先顺序：value > initialValue > {}
          let initVal = value ?? initialValue ?? {};
          try {
            if (typeof initVal === 'string') {
              initVal = JSON.parse(initVal);
            }
            editorRef.current.set(initVal);
          } catch (e) {
            console.error('Invalid initial JSON:', e);
          }

          return () => editorRef.current?.destroy();
        }, []);

        // 外部 value 更新时同步
        useEffect(() => {
          if (!editorRef.current || value === undefined) return;

          try {
            const newValue = typeof value === 'string' ? JSON.parse(value) : value;
            const current = editorRef.current.get();
            if (JSON.stringify(current) !== JSON.stringify(newValue)) {
              editorRef.current.update(newValue);
            }
          } catch (e) {
            // 忽略
          }
        }, [value]);

        return (
          <div
            ref={containerRef}
            style={{
              width: '100%',
              height,
              border: '1px solid #ddd',
              borderRadius: 6,
            }}
          />
        );
      }}
    />
  );
};

export default ProFormJSONEditor;
